package com.example.wanxiang.service.Impl;

import com.example.wanxiang.dto.MessageDto;
import com.example.wanxiang.entity.Message;
import com.example.wanxiang.repository.MessageRepository;
import com.example.wanxiang.service.MessageService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class MessageImpl implements MessageService {

    @Resource
    private MessageRepository messageRepository;

    @Override
    public Message saveMessage(Message message) {
        return messageRepository.save(message);
    }

    @Override
    public List<Message> getHistoryMessages() {
        return messageRepository.findAll();
    }

    @Override
    public List<Message> findMessagesByChatId(MessageDto messageDto) {
        PageRequest bookList = getRequest(messageDto);
        return getMessagesList(messageRepository.findByChatId(messageDto.getChatId(),bookList));
    }

    @Override
    public long getMessageCount(MessageDto messageDto) {
        return messageRepository.countMessageByChatId(messageDto.getChatId());
    }

    @Override
    public void deleteMessage(String id) {
        messageRepository.deleteById(id);
    }

    public PageRequest getRequest(MessageDto messageDto)
    {
        return  PageRequest.of((int) messageDto.getPage(), (int) messageDto.getSize());
    }

    public List<Message> getMessagesList(Page<Message> messages)
    {
        List<Message> messages1 = new ArrayList<Message>();

        for (Message message : messages) {
            messages1.add(message);
        }
        return messages1;
    }
}
